package service

import (
	/*"net/http"
	"io/ioutil"*/
	"github.com/gin-gonic/gin"
	"encoding/json"
	"net/http"
	"io/ioutil"
	"fmt"
	"talentsystem/model"
	"time"
	"math/rand"
	"github.com/seefan/to"
	"gosugar/sms"
	"github.com/parnurzeal/gorequest"
	"errors"
	"crypto/md5"
	"encoding/hex"
)

type Get struct {
	AccessToken string `json:"access_token"`
	ExpiresIn float64 `json:"expires_in"`
	RefreshToken string `json:"refresh_token"`
	Openid string `json:"openid"`
	Scope string `json:"scope"`
	Errmsg string `json:"errmsg"`
	Errcode int `json:"errcode"`
}
type GetType struct {
	Appid string
	Secret string
	Code string
}
type GetMsg struct {
	Accesstoken string
	Openid string
}
type UserMsg struct {
	 Openid string
	 Nickname string
	 Sex int
	 Province string
	 City string
	 Country string
	 Headimgurl string
	 Unionid string
	 Errcode int
	 Errmsg string
}

type AliType struct {
	Message string `json:"message"`
	Success bool   `json:"success"`
}

type AliyunSMS struct {
	Param        map[string]string // 短信模板的参数,与短信模板占位符对应
	Phone        []string          // 手机号
	SignName     string            // 签名
	TemplateCode string            // 短信模板CODE
	AppCode      string            // 阿里云后台购买api使用权获得
}

func HttpGetUserMsg(c*gin.Context) {
	var param GetMsg
	if er:=c.Bind(&param);er!=nil{
		c.JSON(500,gin.H{
			"satus":500,
			"msg":0,
		})
	}
	resp, err := http.Get("https://api.weixin.qq.com/sns/userinfo?access_token="+param.Accesstoken+"&openid="+param.Openid+"&lang=zh_CN ")
	if err != nil {
		c.JSON(500,gin.H{
			"satus":500,
			"msg":1,
		})
	}
	defer resp.Body.Close()

	body, e := ioutil.ReadAll(resp.Body)
	if e != nil {
		c.JSON(500,gin.H{
			"satus":500,
			"msg":2,
		})
	}
	fmt.Println(string(body))
	//var jsonBlob = []byte(`[{"Name": "Platypus", "Order": "Monotremata"}]`)
	var str ="["+string(body)+"]"
	var jsonBlob = []byte(str)
	var msg []UserMsg
	error:=json.Unmarshal(jsonBlob,&msg)
	/*get:=Get{}
	fmt.Println(string(body))
	msg:=[]byte (string(body))
	error:=json.Unmarshal(msg,&get)*//*
	fmt.Println(get)*/
	if error!=nil{
		c.JSON(500,gin.H{
			"satus":500,
			"msg":3,
			"body":string(body),
		})
		return
	}
	c.JSON(200,gin.H{
		"satus":200,
		"msg":msg,
	})
}
func HttpGet(c*gin.Context) {
	var param GetType
	if er:=c.Bind(&param);er!=nil{
		c.JSON(500,gin.H{
			"satus":500,
			"msg":0,
		})
	}
	resp, err := http.Get("https://api.weixin.qq.com/sns/oauth2/access_token?appid="+param.Appid+"&secret="+param.Secret+"&code="+param.Code+"&grant_type=authorization_code")
	if err != nil {
		c.JSON(500,gin.H{
			"satus":500,
			"msg":1,
		})
	}
	defer resp.Body.Close()
	body, e := ioutil.ReadAll(resp.Body)
	if e != nil {
		c.JSON(500,gin.H{
			"satus":500,
			"msg":2,
		})
	}
	//var jsonBlob = []byte(`[{"Name": "Platypus", "Order": "Monotremata"}]`)
	var str ="["+string(body)+"]"
	var jsonBlob = []byte(str)
	var msg []Get
	error:=json.Unmarshal(jsonBlob,&msg)
	if error!=nil{
		c.JSON(500,gin.H{
			"satus":500,
			"msg":3,
			"body":string(body),
		})
		return
	}
	c.JSON(200,gin.H{
		"satus":200,
		"msg":msg,
	})
}
func ObtainAliyunSmsAuthCode(c *gin.Context){
	var param model.TypePhone
	if err:=c.Bind(&param);err!=nil{
		c.JSON(500,gin.H{
			"status":500,
			"msg":"参数格式不正确",
		})
		return
	}
	//0sign  1 reset
	var templatecode string=""
	if param.Atype==0{
		templatecode="xxxxx"
	}else if param.Atype==1{
		templatecode="xxxx"
	}
	randcode:=RandomNumber(200000, 999999)
	//resp,er:=http.Get("http://sms.market.alicloudapi.com/singleSendSms?ParamString=%7B%22code%22%3A%22"+to.String(randcode)+"%22%2C%22product%22%3A%22%蜜蜂速聘%22%7D&RecNum="+param.Phone+"&SignName=欧酷时代&TemplateCode=SMS_60030349'  -H 'Authorization:61bb3ac37eef48a1bf1568086a6eba3f")
	er:= sms.AliyunSendSMS(&sms.AliyunSMS{
		TemplateCode: templatecode,
		Param: map[string]string{
			"code":    to.String(randcode),
			"product": "xxxx",
		},
		Phone:    []string{param.Phone},
		AppCode:  "xxx",
		SignName: "xxx",
	})
	if er !=nil {
		fmt.Println(er)
		c.JSON(500,gin.H{
			"satus":500,
			"msg":"请求阿里云短信服务失败",
		})
	}
	data := []byte(to.String(randcode))
	md5Ctx := md5.New()
	md5Ctx.Write(data)
	cipherStr := md5Ctx.Sum(nil)
	c.JSON(200,gin.H{
		"status":200,
		"msg":hex.EncodeToString(cipherStr),
	})
	return
}
func RandomNumber(min, max int64) int64 {
	if min > max {
		v := min
		min = max
		max = v
	}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	return r.Int63n(max-min) + min
}
//阿里云短信验证
func AliyunSendSMS(sms *AliyunSMS) error {
	if sms == nil {
		return errors.New("阿里云短信消息体为空")
	}
	if len(sms.Phone) == 0 {
		return errors.New("发送短信最少需要一个手机号")
	}
	if len(sms.AppCode) == 0 {
		return errors.New("阿里云短信消息体缺少AppCode")
	}
	param, err := json.Marshal(sms.Param)
	if err != nil {
		return err
	}
	var phone string
	for i, v := range sms.Phone {
		phone = phone + v
		if i+1 < len(sms.Phone) {
			phone = phone + ","
		}
	}
	request := gorequest.New().Get("http://sms.market.alicloudapi.com/singleSendSms")
	request.Set("Authorization", "APPCODE "+sms.AppCode)
	request.Param("ParamString", string(param))
	request.Param("RecNum", phone)
	request.Param("SignName", sms.SignName)
	request.Param("TemplateCode", sms.TemplateCode)
	_, body, errs := request.End()
	if len(errs) > 0 {
		return errs[0]
	}
	type Result struct {
		Message string `json:"message"`
		Success bool   `json:"success"`
	}
	result := &Result{}
	if err = json.Unmarshal([]byte(body), result); err != nil {
		return err
	}
	if result.Success {
		return nil
	}
	return errors.New(result.Message)
}
//上传文件
func UploadImg(c *gin.Context) {
	err := c.Request.ParseMultipartForm(50000000)
	if err!=nil {
		c.JSON(400,gin.H{
		"satus":400,
		"msg":"文件大小初始化失败",
	   })
	}
	nowtime,error:=c.GetPostForm("time")
	fmt.Println(nowtime)
	if error == false {
		c.JSON(403, gin.H{
			"status": 403,
			"msg":    "时间戳未获取",
		})
		return
	}
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(403, gin.H{
			"status": 403,
			"msg":    "图片未获取",
		})
		return
	}
	/*	timestamp := time.Now().UnixNano()
		tm := time.Unix(timestamp, 0)
		ti := tm.Format("2006010203040501")*/
	num := c.SaveUploadedFile(file, "static/headimages/"+nowtime+file.Filename)
	if num != nil {
		c.JSON(500, gin.H{
			"status": 500,
			"msg":    0,
		})
		return
	}
	c.JSON(200, gin.H{
		"status": 200,
		"msg":  "../headimages/"+ nowtime + file.Filename,
	})
}